package com.lemon.exam.common.util;

import com.lemon.exam.common.exception.CustomException;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.util.StringUtils;

import java.net.*;
import java.util.Enumeration;

/**
 * 请求工具类
 *
 * @author Lemon
 * @since 2025/4/15 15:52
 */
public class RequestUtil {
    /**
     * 获取客户端IP
     *
     * @param request
     * @return
     */
    @SuppressWarnings("ConstantConditions")
    public static String getClientIp(ServerHttpRequest request) {
        //1.从X-Forwarded-For头部获取（经过代理时）
        String ip = request.getHeaders().getFirst("X-Forwarded-For");
        if (StringUtils.hasText(ip) && !"unknown".equalsIgnoreCase(ip)) {
            // 可能有多个IP，取第一个
            return ip.split(",")[0].trim();
        }

        //2.从Proxy-Client-IP头部获取
        ip = request.getHeaders().getFirst("Proxy-Client-IP");
        if (StringUtils.hasText(ip) && !"unknown".equalsIgnoreCase(ip)) {
            return ip;
        }

        //3.从WL-Proxy-Client-IP头部获取（WebLogic）
        ip = request.getHeaders().getFirst("WL-Proxy-Client-IP");
        if (StringUtils.hasText(ip) && !"unknown".equalsIgnoreCase(ip)) {
            return ip;
        }

        //4.从HTTP_CLIENT_IP头部获取
        ip = request.getHeaders().getFirst("HTTP_CLIENT_IP");
        if (StringUtils.hasText(ip) && !"unknown".equalsIgnoreCase(ip)) {
            return ip;
        }

        //5.从HTTP_X_FORWARDED_FOR头部获取
        ip = request.getHeaders().getFirst("HTTP_X_FORWARDED_FOR");
        if (StringUtils.hasText(ip) && !"unknown".equalsIgnoreCase(ip)) {
            return ip;
        }

        // 6. 最后从RemoteAddress获取
        if (request.getRemoteAddress() != null) {
            ip = request.getRemoteAddress().getAddress().getHostAddress();
            // 处理本地测试情况
            if ("0:0:0:0:0:0:0:1".equals(ip) || "127.0.0.1".equals(ip)) {
                try {
                    // 获取本机局域网IP
                    Enumeration<NetworkInterface> interfaces = NetworkInterface.getNetworkInterfaces();
                    while (interfaces.hasMoreElements()) {
                        NetworkInterface iface = interfaces.nextElement();
                        // 排除回环接口和未启用的接口
                        if (iface.isLoopback() || !iface.isUp()) continue;

                        Enumeration<InetAddress> addresses = iface.getInetAddresses();
                        while (addresses.hasMoreElements()) {
                            InetAddress addr = addresses.nextElement();
                            // 排除回环地址和IPv6地址
                            if (addr.isLoopbackAddress() || addr instanceof Inet6Address) continue;

                            String hostAddress = addr.getHostAddress();
                            if (hostAddress != null) {
                                return hostAddress;
                            }
                        }
                    }
                } catch (SocketException e) {
                    //忽略异常
                    return "unknown";
                }
                return "127.0.0.1";
            }
            return ip;
        }
        return "unknown";
    }

    /**
     * 获取服务器IP
     *
     * @return
     */
    public static String getServerIp() {
        try {
            return InetAddress.getLocalHost().getHostAddress();
        } catch (UnknownHostException e) {
            e.printStackTrace();
            throw new CustomException(e.getMessage());
        }
    }
}
